<template>
  <el-dialog
    v-model="dialogVisible"
    title="分配医生"
    width="60%"
    :before-close="handleClose"
    class="assign-doctor-dialog"
  >
    <div class="assign-doctor">
      <!-- 选中记录信息 -->
      <el-card class="records-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>选中记录 ({{ records.length }} 条)</span>
          </div>
        </template>
        
        <div class="records-list">
          <div
            v-for="record in records"
            :key="record.id"
            class="record-item"
          >
            <div class="record-info">
              <div class="record-id">{{ record.id }}</div>
              <div class="record-patient">{{ record.patientName }}</div>
              <div class="record-date">{{ formatDate(record.checkupDate) }}</div>
              <div class="record-current-doctor">
                当前医生: {{ record.doctor || '未分配' }}
              </div>
            </div>
            <el-tag :type="getStatusType(record.status)" size="small">
              {{ getStatusText(record.status) }}
            </el-tag>
          </div>
        </div>
      </el-card>
      
      <!-- 医生选择 -->
      <el-card class="doctor-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>选择医生</span>
            <el-button type="primary" size="small" @click="handleRefreshDoctors">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </template>
        
        <el-form :model="formData" label-width="100px">
          <el-form-item label="分配方式">
            <el-radio-group v-model="assignMode">
              <el-radio label="single">统一分配</el-radio>
              <el-radio label="multiple">分别分配</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <!-- 统一分配模式 -->
          <div v-if="assignMode === 'single'">
            <el-form-item label="选择医生" required>
              <el-select
                v-model="formData.selectedDoctor"
                placeholder="请选择医生"
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="doctor in availableDoctors"
                  :key="doctor.id"
                  :label="`${doctor.name} (${doctor.title})`"
                  :value="doctor.name"
                >
                  <div class="doctor-option">
                    <div class="doctor-info">
                      <span class="doctor-name">{{ doctor.name }}</span>
                      <span class="doctor-title">{{ doctor.title }}</span>
                    </div>
                    <div class="doctor-stats">
                      <span class="workload">工作量: {{ doctor.workload || 0 }}</span>
                    </div>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          
          <!-- 分别分配模式 -->
          <div v-if="assignMode === 'multiple'">
            <div class="multiple-assign">
              <div
                v-for="(record, index) in records"
                :key="record.id"
                class="assign-item"
              >
                <div class="assign-label">
                  {{ record.id }} - {{ record.patientName }}
                </div>
                <el-select
                  v-model="formData.assignments[index]"
                  placeholder="请选择医生"
                  style="width: 200px"
                  filterable
                >
                  <el-option
                    v-for="doctor in availableDoctors"
                    :key="doctor.id"
                    :label="`${doctor.name} (${doctor.title})`"
                    :value="doctor.name"
                  />
                </el-select>
              </div>
            </div>
          </div>
          
          <el-form-item label="分配原因">
            <el-input
              v-model="formData.reason"
              type="textarea"
              :rows="3"
              placeholder="请输入分配原因（可选）"
            />
          </el-form-item>
        </el-form>
      </el-card>
      
      <!-- 医生列表 -->
      <el-card class="doctors-list-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>医生列表</span>
            <el-input
              v-model="doctorSearch"
              placeholder="搜索医生"
              style="width: 200px"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </template>
        
        <div class="doctors-grid">
          <div
            v-for="doctor in filteredDoctors"
            :key="doctor.id"
            class="doctor-card"
            :class="{ 'selected': isSelectedDoctor(doctor) }"
            @click="handleSelectDoctor(doctor)"
          >
            <div class="doctor-avatar">
              <el-avatar :size="48" :src="doctor.avatar">
                <el-icon><User /></el-icon>
              </el-avatar>
            </div>
            <div class="doctor-details">
              <div class="doctor-name">{{ doctor.name }}</div>
              <div class="doctor-title">{{ doctor.title }}</div>
              <div class="doctor-department">{{ doctor.department }}</div>
              <div class="doctor-workload">
                <el-progress
                  :percentage="getWorkloadPercentage(doctor.workload)"
                  :stroke-width="6"
                  :show-text="false"
                />
                <span class="workload-text">工作量: {{ doctor.workload || 0 }}</span>
              </div>
            </div>
            <div class="doctor-status">
              <el-tag
                :type="doctor.status === 'available' ? 'success' : 'warning'"
                size="small"
              >
                {{ doctor.status === 'available' ? '可用' : '忙碌' }}
              </el-tag>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">
          <el-icon><Check /></el-icon>
          确认分配
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  records: {
    type: Array,
    default: () => []
  },
  doctors: {
    type: Array,
    default: () => []
  }
})

// Emits
const emit = defineEmits(['update:visible', 'success'])

// 响应式数据
const assignMode = ref('single')
const doctorSearch = ref('')

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 表单数据
const formData = reactive({
  selectedDoctor: '',
  assignments: [],
  reason: ''
})

// 扩展医生数据
const availableDoctors = computed(() => {
  return props.doctors.map(doctor => ({
    ...doctor,
    department: doctor.department || '内科',
    workload: Math.floor(Math.random() * 20), // 模拟工作量
    status: Math.random() > 0.3 ? 'available' : 'busy', // 模拟状态
    avatar: ''
  }))
})

// 过滤医生
const filteredDoctors = computed(() => {
  if (!doctorSearch.value) {
    return availableDoctors.value
  }
  
  const keyword = doctorSearch.value.toLowerCase()
  return availableDoctors.value.filter(doctor => 
    doctor.name.toLowerCase().includes(keyword) ||
    doctor.title.toLowerCase().includes(keyword) ||
    doctor.department.toLowerCase().includes(keyword)
  )
})

// 监听对话框显示状态
watch(() => props.visible, (visible) => {
  if (visible) {
    initFormData()
  }
})

// 监听分配模式变化
watch(assignMode, (mode) => {
  if (mode === 'multiple') {
    formData.assignments = new Array(props.records.length).fill('')
  }
})

// 方法
const initFormData = () => {
  formData.selectedDoctor = ''
  formData.assignments = new Array(props.records.length).fill('')
  formData.reason = ''
  assignMode.value = 'single'
}

const handleClose = () => {
  dialogVisible.value = false
}

const handleRefreshDoctors = () => {
  ElMessage.success('医生列表已刷新')
}

const handleSelectDoctor = (doctor) => {
  if (assignMode.value === 'single') {
    formData.selectedDoctor = doctor.name
  }
}

const isSelectedDoctor = (doctor) => {
  if (assignMode.value === 'single') {
    return formData.selectedDoctor === doctor.name
  }
  return formData.assignments.includes(doctor.name)
}

const handleSubmit = async () => {
  // 验证表单
  if (assignMode.value === 'single') {
    if (!formData.selectedDoctor) {
      ElMessage.warning('请选择医生')
      return
    }
  } else {
    const unassigned = formData.assignments.some(assignment => !assignment)
    if (unassigned) {
      ElMessage.warning('请为所有记录分配医生')
      return
    }
  }
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新记录的医生分配
    if (assignMode.value === 'single') {
      props.records.forEach(record => {
        record.doctor = formData.selectedDoctor
      })
    } else {
      props.records.forEach((record, index) => {
        record.doctor = formData.assignments[index]
      })
    }
    
    ElMessage.success('医生分配成功')
    emit('success')
    handleClose()
  } catch (error) {
    ElMessage.error('分配失败，请重试')
  }
}

const getStatusType = (status) => {
  const statusMap = {
    pending: 'warning',
    in_progress: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    pending: '待体检',
    in_progress: '体检中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || '未知'
}

const getWorkloadPercentage = (workload) => {
  return Math.min((workload / 20) * 100, 100)
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}
</script>

<style scoped>
.assign-doctor-dialog :deep(.el-dialog__body) {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.assign-doctor {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.records-card,
.doctor-card,
.doctors-list-card {
  border: 1px solid #e4e7ed;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #2c3e50;
}

.records-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: 200px;
  overflow-y: auto;
}

.record-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.record-info {
  display: flex;
  gap: 16px;
  align-items: center;
  flex: 1;
}

.record-id {
  font-weight: 600;
  color: #2c3e50;
  min-width: 80px;
}

.record-patient {
  font-weight: 500;
  color: #495057;
  min-width: 100px;
}

.record-date {
  color: #6c757d;
  min-width: 100px;
}

.record-current-doctor {
  color: #6c757d;
  font-size: 13px;
}

.multiple-assign {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.assign-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.assign-label {
  font-weight: 500;
  color: #2c3e50;
  min-width: 200px;
}

.doctor-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.doctor-info {
  display: flex;
  flex-direction: column;
}

.doctor-name {
  font-weight: 500;
  color: #2c3e50;
}

.doctor-title {
  font-size: 12px;
  color: #6c757d;
}

.doctor-stats {
  font-size: 12px;
  color: #6c757d;
}

.doctors-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  max-height: 400px;
  overflow-y: auto;
}

.doctor-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #ffffff;
  cursor: pointer;
  transition: all 0.3s ease;
}

.doctor-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.doctor-card.selected {
  border-color: #409eff;
  background: #ecf5ff;
}

.doctor-avatar {
  flex-shrink: 0;
}

.doctor-details {
  flex: 1;
  min-width: 0;
}

.doctor-details .doctor-name {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
  margin-bottom: 4px;
}

.doctor-details .doctor-title {
  color: #6c757d;
  font-size: 12px;
  margin-bottom: 2px;
}

.doctor-details .doctor-department {
  color: #6c757d;
  font-size: 12px;
  margin-bottom: 8px;
}

.doctor-workload {
  display: flex;
  align-items: center;
  gap: 8px;
}

.workload-text {
  font-size: 11px;
  color: #6c757d;
  white-space: nowrap;
}

.doctor-status {
  flex-shrink: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .assign-doctor-dialog {
    width: 95% !important;
  }
  
  .assign-doctor-dialog :deep(.el-dialog__body) {
    padding: 15px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .record-info {
    flex-direction: column;
    gap: 4px;
    align-items: flex-start;
  }
  
  .record-id,
  .record-patient,
  .record-date {
    min-width: auto;
  }
  
  .assign-item {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .assign-label {
    min-width: auto;
  }
  
  .doctors-grid {
    grid-template-columns: 1fr;
  }
  
  .doctor-card {
    flex-direction: column;
    text-align: center;
  }
  
  .doctor-workload {
    justify-content: center;
  }
  
  .dialog-footer {
    flex-direction: column;
  }
  
  .dialog-footer .el-button {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .record-item {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .doctor-details {
    width: 100%;
  }
  
  .doctor-workload {
    flex-direction: column;
    gap: 4px;
  }
}
</style>